package cn.ultrarisk.booyo.core.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * IOUtil
 *
 * @author sevendlong(lin23871@163.com)
 * @date 2014/9/18
 * @since V1.0
 */
public class IOUtil {
    /**
     * 将输入流(InputStream)转为byte数组，读取完后输入流(InputStream)即被关闭
     *
     * @param in 输入流
     * @return 返回byte数组
     * @throws java.io.IOException
     */
    public static byte[] in2Bytes(InputStream in) throws IOException {
        if (in == null) {
            return null;
        }

        ByteArrayOutputStream out = null;
        byte[] bytes = null;
        try {
            out = new ByteArrayOutputStream();
            byte[] buffer = new byte[2048];
            int len;
            while ((len = in.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
            bytes = out.toByteArray();
        } finally {
            if (out != null) {
                out.close();
            }
            in.close();
        }

        return bytes;
    }

    public static String in2Str(InputStream in) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int i;
        while ((i = in.read()) != -1) {
            baos.write(i);
        }
        return baos.toString();
    }
}
